const Service = require('egg').Service;
const HttpException = require('../../exception/http');
class UserService extends Service {
	tableName = 'product-table';
    async queryProduct(data = {}) {
        // 用户关联产品，只有当前用户下的产品才会查出来
        const { ctx } = this;
        const username = ctx.state.user.username;
		const products = await this.app.mongo.find(this.tableName, {
			query: { ...data, username }
        });
        // 返回处理一下
        const productVo = products.map(product => {
            delete product.username;
            return product;
        })
		return productVo;
	}
	// 创建产品
	async createProduct(data = {}) {
		const { app, ctx } = this;
        const { productName, productDesc, status } = data;
        const username = ctx.state.user.username;
        // 创建的时候关联用户
        const createTime = ctx.helper.getCurrentTime();
        
		const res = await app.mongo.insertOne(this.tableName, {
			doc: { username, productName, status: status ? 1 : 0, productDesc, createTime }
		});
		return res;
	}
	// 更新产品
    async updateProduct(data) {
        const { app, ctx } = this;
        const { productName, productDesc, status, _id } = data;
        const username = ctx.state.user.username;
        // 创建的时候关联用户
		// const createTime = ctx.helper.getCurrentTime();
        const res = await app.mongo.findOneAndUpdate(this.tableName, {
            filter: { _id: app.getObjectId(_id) },
            update: {
				$set: { productName, status: status ? 1 : 0, productDesc }
			}
        });
		return res;
    }
	// 根据id删除产品
	async deleteProduct(id) {
		const { app, ctx } = this;
		const objectId = app.getObjectId(id);
		const user = await app.mongo.findOne(this.tableName, {
			query: { _id: objectId }
		});
		const res = await app.mongo.findOneAndDelete(this.tableName, {
			filter: { _id: app.getObjectId(id) }
		});
		return res;
	}
}

module.exports = UserService;
